package main.com.cyz.BinarySearch;

/**
 * @author fox
 * @version 1.0
 * @description
 * 乐扣34
 * 给你一个按照非递减顺序排列的整数数组 nums，和一个目标值 target。请你找出给定目标值在数组中的开始位置和结束位置。
 *
 * 如果数组中不存在目标值 target，返回 [-1, -1]。
 *
 * 你必须设计并实现时间复杂度为 O(log n) 的算法解决此问题。
 *
 *
 *
 * 示例 1：
 *
 * 输入：nums = [5,7,7,8,8,10], target = 8
 * 输出：[3,4]
 * 示例 2：
 *
 * 输入：nums = [5,7,7,8,8,10], target = 6
 * 输出：[-1,-1]
 * 示例 3：
 *
 * 输入：nums = [], target = 0
 * 输出：[-1,-1]
 *
 *
 * 提示：
 *
 * 0 <= nums.length <= 105
 * -109 <= nums[i] <= 109
 * nums 是一个非递减数组
 * -109 <= target <= 109
 * @date 2024/5/17 8:53
 */

//考察二分查找寻找最左最右
public class LeetCode34 {

    public static int[] searchRange(int[] nums, int target) {

        return new int[]{leftMost(nums,target),rightMost(nums,target)};

    }

    private static int leftMost(int[] nums, int target) {

        int start = 0;
        int end = nums.length - 1;
        int result = -1;

        while(start <= end){
            int mid = (start + end) >>> 1;
            if(target == nums[mid]){
                result = mid;
                end = mid - 1;
            }else if(target < nums[mid]){
                end = mid - 1;
            }else{
                start = mid + 1;
            }
        }

        return result;
    }

    private static int rightMost(int[] nums, int target) {

        int start = 0;
        int end = nums.length - 1;
        int result = -1;

        while(start <= end){
            int mid = (start + end) >>> 1;
            if(target == nums[mid]){
                result = mid;
                start = mid + 1;
            }else if(target < nums[mid]){
                end = mid - 1;
            }else{
                start = mid + 1;
            }
        }

        return result;
    }

}
